import { useEffect, useRef } from 'react';
import type { MotionEvent } from '../interface';

export default function useDomMotionEvents(
  callback: (event: MotionEvent) => void,
): [(element: HTMLElement) => void, (element: HTMLElement) => void] {
  const cacheElementRef = useRef<HTMLElement>();

  function removeMotionEventsListener(element: HTMLElement) {
    if (element) {
      element.removeEventListener('transitionend', callback);
      element.removeEventListener('animationend', callback);
    }
  }

  function addMotionEventsListener(element: HTMLElement) {
    if (cacheElementRef.current && cacheElementRef.current !== element) {
      removeMotionEventsListener(cacheElementRef.current);
    }

    if (element && element !== cacheElementRef.current) {
      element.addEventListener('transitionend', callback);
      element.addEventListener('animationend', callback);

      cacheElementRef.current = element;
    }
  }

  useEffect(() => {
    return () => {
      if (cacheElementRef.current) {
        removeMotionEventsListener(cacheElementRef.current);
      }
    };
  }, []);

  return [addMotionEventsListener, removeMotionEventsListener];
}
